#!/usr/bin/env python

import sys
import os
from optparse import OptionParser

workingFileLine = 1
revisionLine = 10

def run(command):
    return os.popen(command).readlines()

def getRevision(record):
    i = revisionLine
    dates = []
    while i < len(record):
        if record[i].startswith('date:'):
            dates.append((record[i], record[i-1]))
        i += 1
    dates.sort()
    return dates[-1][1].strip()

def main(args=None):
    if args == None:
        args = sys.argv[1:]

    parser = OptionParser(usage='usage: %prog <Issue#>')
    parser.add_option('-u', action='store', dest='user', default=None,
                      help='only find log entries from this user')

    (options, args) = parser.parse_args(args)
    options.issue = '81293'

    if len(args) > 0:
        options.issue = args[0]

    if options.user:
        command = 'cvs -q log -N -w%(user)s'
    else:
        command = 'cvs -q log -N'

    lines = run(command % vars(options))

    i = 0
    while i < len(lines):
        if -1 != lines[i].find('RCS file:'):
            # starting a record
            record = [lines[i]]
            i += 1
            while -1 == lines[i].find('==========' ):                    
                record.append(lines[i])
                i += 1
            for r in record:
                if -1 != r.find(options.issue):
                    if len(record) > revisionLine:
                        revision = getRevision(record)
                        workingFile = record[workingFileLine].split(':')[1].strip()
                        print  workingFile, revision
                    break
        i += 1

    return 0
                      

if __name__ == '__main__':
    sys.exit(main())

